package api

import (
	"github.com/LyricTian/gin-admin/v7/internal/app/ginx"
	"github.com/LyricTian/gin-admin/v7/internal/app/schema"
	"github.com/LyricTian/gin-admin/v7/internal/lib/cache"
	"github.com/LyricTian/gin-admin/v7/internal/lib/pay"
	"github.com/LyricTian/gin-admin/v7/internal/lib/weapp"
	"github.com/LyricTian/gin-admin/v7/internal/lib/wechat"
	"github.com/LyricTian/gin-admin/v7/pkg/errors"
	"github.com/LyricTian/gin-admin/v7/pkg/utilx"
	"github.com/gin-gonic/gin"
)

func (a *Order) PayH5(c *gin.Context) {
	url, err := wechat.WeChatPayH5()
	if err != nil {
		ginx.ResError(c, err)
	}
	wechat.Jump(c, url)

}

func (a *Order) PayWeApp(c *gin.Context) {
	//初始化微信客户端
	//    appId：应用ID
	//    mchId：商户ID
	//    apiKey：API秘钥值
	//    isProd：是否是正式环境

	ctx := c.Request.Context()

	money := utilx.S(c.Query("money")).DefaultInt(100)
	openId := c.DefaultQuery("openid", "oDLogxPI6CYkvZKjJfvzt30muvj0")

	data, err := a.OrderBll.WeAppPay(ctx, openId, money)

	if err != nil {
		ginx.ResError(c, err)
		c.Abort()
		return
	}
	//添加订单信息

	//支付回调
	_, err = a.OrderBll.Create(ctx, schema.Order{
		UserId:     ginx.GetUserID(c),
		Creator:    ginx.GetUserID(c),
		OutOrderId: data.OutOrderId,
		Status:     1,
		PayType:    1,
		Money:      money,
	})
	if err != nil {
		ginx.ResError(c, errors.New400Response("创建订单失败"))
		c.Abort()
		return
	}

	ginx.ResSuccess(c, data)

}

func (a *Order) WeAppPayNotify(c *gin.Context) {
	item := new(pay.Notify)
	err := c.BindXML(item)
	if err != nil {
		c.XML(200, map[string]string{
			"return_code": "FAIL",
			"return_msg":  err.Error(),
		})
		c.Abort()
		return
	}

	ctx := c.Request.Context()

	ok, msg := item.IsSuccess(a.SetModel.GetValue(ctx, "wechat", "api_key", ""))
	if ok {
		c.XML(200, map[string]string{
			"return_code": "FAIL",
			"return_msg":  msg,
		})
		c.Abort()
		return
	}
	orderInfo, err := a.OrderBll.GetFirst(ctx, schema.OrderQueryParam{
		Status:     1,
		OutOrderId: item.OutTradeNo,
	})
	if err != nil {
		c.XML(200, map[string]string{
			"return_code": "FAIL",
			"return_msg":  err.Error(),
		})
		c.Abort()
		return
	}

	orderInfo.Status = 2
	orderInfo.InterOrderId = item.TransactionId
	err = a.OrderBll.Update(ctx, orderInfo.ID, *orderInfo)
	if err != nil {
		c.XML(200, map[string]string{
			"return_code": "FAIL",
			"return_msg":  err.Error(),
		})
		c.Abort()
		return
	}

	c.XML(200, map[string]string{
		"return_code": "SUCCESS",
		"return_msg":  "OK",
	})

}

func (a *Order) Login(c *gin.Context) {

	ctx := c.Request.Context()

	data, err := a.SetModel.Query(ctx, schema.SetQueryParam{Category: "wechat"})
	if err != nil {
		ginx.ResError(c, errors.New500Response(err.Error()))
		c.Abort()
		return
	}
	m := data.Data.GetCategory("wechat")

	code := c.Query("code")

	resp, err := weapp.Login(m["app_id"], m["secret"], code)
	if err != nil {
		ginx.ResError(c, errors.New500Response(err.Error()))
		c.Abort()
		return
	}
	ginx.ResSuccess(c, resp)
}

func (a *Order) GetAccessToken(c *gin.Context) {

	ctx := c.Request.Context()

	access_token := cache.Get("access_token")
	if access_token == nil {
		data, err := a.SetModel.Query(ctx, schema.SetQueryParam{Category: "wechat"})
		if err != nil {
			ginx.ResError(c, errors.New500Response("查询配置错误："+err.Error()))
			c.Abort()
			return
		}
		m := data.Data.GetCategory("wechat")

		if len(m["app_id"]) == 0 || len(m["secret"]) == 0 {
			ginx.ResError(c, errors.New500Response("请配置小程序参数"))
			c.Abort()
			return
		}

		resp, err := weapp.GetAccessToken(m["app_id"], m["secret"])
		if err != nil {
			ginx.ResError(c, errors.New500Response("获取token错误："+err.Error()))
			c.Abort()
			return
		}

		cache.Set("access_token", resp, resp.ExpiresIn*1000)

		ginx.ResSuccess(c, resp)
		c.Abort()
		return
	}
	ginx.ResSuccess(c, access_token)

}
